/**
 * 网络请求工具类：兼容表单格式（登录等旧接口）和JSON格式（工单等新接口）
 */
export default {
  baseURL: {
    user: 'http://localhost:6008/user-client',    // 用户模块接口基础路径
    order: 'http://localhost:6013/order-client'   // 工单模块接口基础路径
  },

  /**
   * 默认POST请求（表单格式，保持原有逻辑，确保登录等接口正常）
   * 后端用@RequestParam接收参数的接口用这个方法
   */
  post(url, data = {}, isOrderModule = false) {
    return new Promise((resolve, reject) => {
      const basePath = isOrderModule ? this.baseURL.order : this.baseURL.user;
      const fullUrl = basePath + url;
      console.log('表单请求URL:', fullUrl);

      // 拼接form-data格式参数（原有逻辑，登录接口依赖这个）
      let formData = '';
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          formData += `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}&`;
        }
      }
      formData = formData.slice(0, -1);

      const header = {
        'Content-Type': 'application/x-www-form-urlencoded' // 恢复为表单格式
      };
      const token = uni.getStorageSync('token');
      if (token) {
        header['Token'] = token;
      }

      uni.request({
        url: fullUrl,
        method: 'POST',
        data: formData,
        header: header,
        success: (res) => {
          const result = res.data || {};
          if (result.code === 0) {
            resolve(result.data);
          } else if (result.code !== undefined) {
            reject({ type: 'business', msg: result.msg || '操作失败', code: result.code });
          } else {
            reject({ type: 'http', msg: `请求失败 (${res.statusCode})`, statusCode: res.statusCode });
          }
        },
        fail: (err) => {
          reject({ type: 'network', msg: '网络异常', error: err });
        }
      });
    });
  },

  /**
   * 新增：JSON格式POST请求
   * 后端用@RequestBody接收参数的接口（如工单创建）用这个方法
   */
  postJson(url, data = {}, isOrderModule = false) {
    return new Promise((resolve, reject) => {
      const basePath = isOrderModule ? this.baseURL.order : this.baseURL.user;
      const fullUrl = basePath + url;
      console.log('JSON请求URL:', fullUrl);

      const header = {
        'Content-Type': 'application/json' // JSON格式
      };
      const token = uni.getStorageSync('token');
      if (token) {
        header['Token'] = token;
      }

      uni.request({
        url: fullUrl,
        method: 'POST',
        data: data, // 直接传对象，自动转为JSON
        header: header,
        success: (res) => {
          const result = res.data || {};
          if (result.code === 0) {
            resolve(result.data);
          } else if (result.code !== undefined) {
            reject({ type: 'business', msg: result.msg || '操作失败', code: result.code });
          } else {
            reject({ type: 'http', msg: `请求失败 (${res.statusCode})`, statusCode: res.statusCode });
          }
        },
        fail: (err) => {
          reject({ type: 'network', msg: '网络异常', error: err });
        }
      });
    });
  },

  /**
   * GET请求（保持原有逻辑）
   */
  get(url, params = {}, isOrderModule = false) {
    return new Promise((resolve, reject) => {
      const basePath = isOrderModule ? this.baseURL.order : this.baseURL.user;
      const fullUrl = basePath + url;

      const header = {};
      const token = uni.getStorageSync('token');
      if (token) {
        header['Token'] = token;
      }

      uni.request({
        url: fullUrl,
        method: 'GET',
        data: params,
        header: header,
        success: (res) => {
          const result = res.data || {};
          if (result.code === 0) {
            resolve(result.data);
          } else {
            reject({ type: 'business', msg: result.msg || '操作失败' });
          }
        },
        fail: (err) => {
          reject({ type: 'network', msg: '网络异常' });
        }
      });
    });
  }
};
